<template>
  <!-- 添加和修改章节表单 -->
  <el-dialog :visible="dialogVisible" :title="dialogTitle" @close="close()">
    <el-form :model="video" :rules="rules" ref="videoForm" label-width="80px">
      <el-form-item label="课时标题" prop="title">
        <el-input v-model="video.title" style="width: 400px" @keyup.enter.native="saveOrUpdate()"/>
      </el-form-item>
      <el-form-item label="课时排序">
        <el-input-number :min="0" v-model="video.sort" controls-position="right" style="width: 140px"/>
      </el-form-item>
      <el-form-item label="是否免费">
        <el-radio-group v-model="video.free" size="small">
          <el-radio-button :label="true">免费</el-radio-button>
          <el-radio-button :label="false">默认</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="上传视频">
        <el-upload
          ref="upload"
          :auto-upload="false"
          :on-change="handleChange"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-exceed="handleUploadExceed"
          :before-remove="handleBeforeRemove"
          :on-remove="handleOnRemove"
          :file-list="fileList"
          :limit="1"
          :action="uploadAction"
          style="width: 400px"
        >
          <el-button slot="trigger" size="small" type="success">选择视频</el-button>
          <el-button
            :disabled="uploadBtnDisabled"
            style="margin-left: 10px;"
            size="small"
            type="primary"
            @click="submitUpload()"
          >上传
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" @click="saveOrUpdate()">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { vodApi, videoApi } from '@/api'

export default {
  data() {
    return {
      dialogVisible: false, // 是否显示对话框
      dialogTitle: '添加课时', // 对话框标题
      video: {
        title: '',
        sort: 0,
        free: false
      },
      fileList: [], //上传文件列表
      uploadBtnDisabled: true, // 禁用上传按钮
      uploadFlag: false, // 是否已经上传视频
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      },
      uploadAction: process.env.VUE_APP_BASE_API + '/admin/aliyun/vod/'
    }
  },
  methods: {
    open(chapterId, videoId) {
      this.uploadFlag = false
      this.dialogVisible = true
      this.video.chapterId = chapterId
      this.dialogTitle = '添加课时'
      if (videoId) {
        console.log(videoId)
        videoApi.queryById(videoId).then(response => {
          this.video = response.data.item
          this.dialogTitle = '修改课时'
          // 回显
          if (this.video.videoOriginalName) {
            this.fileList = [{ 'name': this.video.videoOriginalName }]
          }
        })
      }
    },
    close() {
      this.dialogVisible = false
      // 重置表单
      this.resetForm()
    },
    resetForm() {
      this.video = {
        title: '',
        sort: 0,
        free: false
      }
      this.fileList = [] // 重置视频上传列表
    },
    // 保存或更新
    saveOrUpdate() {
      this.$refs.videoForm.validate((valid) => {
        if (valid) {
          if (!this.video.id) {
            this.saveData()
          } else {
            this.updateData()
          }
        } else {
          this.$message.warning('请完成必填项')
        }
      })
    },
    saveData() {
      this.video.courseId = this.$parent.$parent.courseId
      videoApi.insert(this.video).then(response => {
        this.$message.success(response.message)
        // 关闭组件
        this.close()
        // 刷新列表
        this.$parent.fetchTreeList()
      })
    },
    updateData() {
      videoApi.update(this.video).then(response => {
        this.$message.success(response.message)
        // 关闭组件
        this.close()
        // 刷新列表
        this.$parent.fetchTreeList()
      })
    },
    // 添加文件,上传成功,上传失败时
    handleChange(file, fileList) {
      if (!this.uploadFlag) {
        this.uploadBtnDisabled = false
      }
    },
    // 上传多于一个视频时
    handleUploadExceed(files, fileList) {
      this.$message.warning('请先删除已上传的视频')
    },
    // 上传
    submitUpload() {
      this.uploadBtnDisabled = true
      this.$refs.upload.submit() // 提交上传请求
    },
    // 视频上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.success) {
        this.video.videoSourceId = response.data.videoId
        this.video.videoOriginalName = file.name
        this.$message.success('上传视频成功')
        this.uploadFlag = true
      } else {
        this.$message.error('上传视频失败（非HTTP错误)')
        this.uploadFlag = false
      }
    },
    // 失败
    handleUploadError() {
      this.$message.error('上传视频失败（HTTP错误)')
      this.uploadFlag = false
    },
    // 删除视频前
    handleBeforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 删除视频时
    handleOnRemove(file, fileList) {
      if (this.video.videoSourceId) {
        console.log(this.video.videoSourceId)
        // 从阿里云vod删除视频
        vodApi.deleteVOD(this.video.videoSourceId).then(response => {
          this.video.videoSourceId = ''
          this.video.videoOriginalName = ''
          videoApi.update(this.video)
          this.$message.success(response.message)
        }).catch(() => {
          this.video.videoSourceId = ''
          this.video.videoOriginalName = ''
          videoApi.update(this.video)
        })
      }
      this.uploadBtnDisabled = true
      this.uploadFlag = false
    }
  }
}
</script>

<style scoped>

</style>
